package com.sunpy.permissionservice.login.filter;

import com.sunpy.commonservice.util.JwtUtil;
import com.sunpy.commonservice.util.RedisCache;
import com.sunpy.permissionservice.login.model.LoginUserDetailBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *  token续签
 * </p>
 *
 * @author sunpy
 * @since 2022-09-260
 */
@Slf4j
@Order(1)
@Component
public class RefreshTokenFilter implements Filter {

    @Value("${sys.login-uri}")
    private String loginUri;

    @Value("${sys.login-jwt.expire}")
    private int expireJWT;

    @Value("${sys.login-redis.expire}")
    private int expireRedis;

    @Autowired
    private RedisCache redisCache;

    @Value("${sys.login-redis.delay}")
    private long delayTime;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("+++++++++++++++++++RefreshTokenFilter.doFilter");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String token = req.getHeader("token");

        if (loginUri.equals(req.getRequestURI()) || StrUtil.isBlank(token)) {
            chain.doFilter(req, resp);
            return;
        }

        String userId = (String) JwtUtil.parseJWT(token).get("userId");
        LoginUserDetailBO loginUserDetailBO = redisCache.getCacheObject("token:" + userId);
        long time = redisCache.getExpireTime("token:" + userId);

        if (time < delayTime) {
            if (redisCache.deleteObject("token:" + userId)) {
                String newJWT = JwtUtil.createJWT("token:" + userId, loginUserDetailBO, expireJWT);
                redisCache.setCacheObject("token:" + userId, loginUserDetailBO);
                redisCache.expire("token:" + userId, expireRedis);
                resp.setHeader("token", newJWT);
                chain.doFilter(req, resp);
                return;
            }

            resp.setHeader("token", token);
            chain.doFilter(req, resp);
            return;
        }

        chain.doFilter(req, resp);
    }

}
